package com.app.service.impl;

import com.app.domain.po.ViewPo;
import com.app.domain.vo.ViewVo;
import com.app.framework.utils.RedisUtils;
import com.app.mapper.ViewMapper;
import com.app.service.ViewService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * Web访问方法实现
 */
@Service
public class ViewServiceImpl extends ServiceImpl<ViewMapper, ViewPo> implements ViewService {

    /**
     * 增加访问量
     */
    @Override
    public void look() {
        String redisKey = "view_count";
        if (RedisUtils.hasKey(redisKey)) {
            //访问时候Redis+1
            RedisUtils.increment(redisKey);
        }
    }

    /**
     * 获取访问量
     */
    @Override
    public Integer view() {
        String redisKey = "view_count";
        if (RedisUtils.hasKey(redisKey)) {
            Object value = RedisUtils.get(redisKey);
            return (Integer) value;
        } else {
            ViewPo viewPo = baseMapper.getOne();
            RedisUtils.set(redisKey, viewPo.getView());
            return viewPo.getView();
        }
    }

    /**
     * 网站信息统计
     */
    @Override
    @Cacheable(cacheNames = "web_count", key = "'count'", cacheManager = "cache6Hour")
    public ViewVo webCount() {
        //建站日期
        String BASE_STATION = "2018-10-10";
        //将字符串转换为LocalDate
        LocalDate baseStationDate = LocalDate.parse(BASE_STATION, DateTimeFormatter.ISO_LOCAL_DATE);
        //获取当前日期
        LocalDate currentDate = LocalDate.now();
        //计算日期差异
        long daysDifference = currentDate.toEpochDay() - baseStationDate.toEpochDay();
        ViewVo viewVo = baseMapper.selectWebCount();
        viewVo.setStation((int) daysDifference);
        return viewVo;
    }

    //--------------------------------------------------------------|↓|持久化到数据库|↓|-----------------------------------------------------------------
    //--------------------------------------------------------------|↓|持久化到数据库|↓|-----------------------------------------------------------------
    //--------------------------------------------------------------|↓|持久化到数据库|↓|-----------------------------------------------------------------

    /**
     * 持久化到数据库(每6个小时)
     */
    @Async
    @Scheduled(cron = "0 0 */6 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void updateViewLookCount() {
        String redisKey = "view_count";
        if (RedisUtils.hasKey(redisKey)) {
            Object value = RedisUtils.get(redisKey);
            ViewPo viewPo = baseMapper.getOne();
            viewPo.setView((Integer) value);
            baseMapper.updateById(viewPo);
        }
    }

}